﻿using Common.Communal;
using ERP.Domain.System;
using MediatR;
using SqlSugar;
using System.Api.Read.Applications.Commands.Users;
using System.DTO;

namespace System.Api.Read.Applications.CommandHandlers.Users
{
    /// <summary>
    /// 用户查询命令处理程序
    /// </summary>
    public class UsersQueryCommandHandler : IRequestHandler<UsersQueryCommand, ApiResult<ApiPaging<UserRoleDTO>>>
    {
        private readonly ISqlSugarClient sqlSugar;

        public UsersQueryCommandHandler(ISqlSugarClient sqlSugar)
        {
            this.sqlSugar = sqlSugar;
        }

        public Task<ApiResult<ApiPaging<UserRoleDTO>>> Handle(UsersQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<UserRoleDTO>> result = new ApiResult<ApiPaging<UserRoleDTO>>();
            var res = sqlSugar.Queryable<User>().
                LeftJoin<UserRole>((a, b) => a.Id == b.UserId).
                LeftJoin<Role>((a, b, c) => b.RoleId == c.Id).
                LeftJoin<Organize>((a, b, c, d) => a.OrganzationNo == d.OrganizeNo).
                LeftJoin<Post>((a, b, c, d, e) => a.PostNo == e.PostNo).Where((a, b, c, d, e) => a.IsDeleted == false)
                .Select((a, b, c, d, e) => new UserRoleDTO
                {
                    Id = a.Id,
                    UserNo = a.UserNo,
                    UserName = a.UserName,
                    OrganzationNo = a.OrganzationNo,
                    OrganizeName = d.OrganizeName,
                    PostNo = a.PostNo,
                    RoleName = c.RoleName,
                    UserAccount = a.UserAccount,
                    UserPassword = a.UserPassword,
                    UserSex = a.UserSex,
                    UserPhone = a.UserPhone,
                    UserEmail = a.UserEmail,
                    UserStatus = a.UserStatus,
                    PostName = e.PostName,
                    IsDeleted = a.IsDeleted
                });
            // 根据用户名称或账户进行模糊查询
            if (!string.IsNullOrWhiteSpace(request.UserNameAccount))
            {
                res = res.Where(a => a.UserName.Contains(request.UserNameAccount) || a.UserNo.Contains(request.UserNameAccount));
            }
            // 根据用户状态进行精确查询
            if (request.UserStatus!=null)
            {
                res = res.Where(a => a.UserStatus == request.UserStatus);
            }
            int count = res.Count();
            int page = (int)Math.Ceiling(count * 1.0 / request.Size);
            var list = res.OrderBy(a => a.Id).Skip((request.Index - 1) * request.Size).Take(request.Size);
            ApiPaging<UserRoleDTO> paging = new ApiPaging<UserRoleDTO>()
            {
                TotalCount = count,
                TotalPage = page,
                Data = list.ToList()
            };
            result.Success(paging, result.Message = "用户查询成功");
            return Task.FromResult(result);
        }
    }
}
